//文章发布页面
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { PlusOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import './index.scss'

import {publishActiveAPI,getActiveByIdAPI,updateActiveByIdAPI} from  '@/apis/active'
import {baseURL} from '@/utils'
import { useNavigate,useSearchParams } from "react-router-dom";

import {  useEffect, useState } from 'react'
import {useChannel } from '@/hooks/useChannel'
import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select,
    message
  } from 'antd'

  
  const { Option } = Select

  

const Publish = () => {

    //获取评到列表
    const {channelList} = useChannel()

    //获取跳转方式
    const navigate  = useNavigate()
   //获取表单数据
   const onFinish  =async (date)=>{
    //判断图片提交的类型和个数是否相同
    if(imgeType !== imageList.length){
      console.log('为什么',imgeType,imageList.length,typeof imgeType ,typeof imageList.length)
        //不相同后面的代码就不执行了
        return  message.warning('图片类型和数量不一致')
    }

    //组织表单数据
    const fromDate ={
        title:  date.title,
        content: date.content,
        cover:{
            type:imgeType, //封面模式
            //这里的ur1处理逻辑只是在新增时候的逻辑
            //编辑的时候需要做处理
            images: imageList.map(item => {
                if (item.response) {
                  return item.response.data.url
                } else {
                  return item.url
                }
              }) // 图片列表 
        },
        channel_id: date.channel_id
    }

    //处理调用不同的接口新增-新增接口编辑状态-更新接口id
    if(articleId){
      //存在为更新
      await updateActiveByIdAPI({
        ...fromDate,
        id: articleId
      })
      message.success(  '更新成功' )
    }else{
      //新增数据
      await publishActiveAPI(fromDate)
      message.success(  '发布成功' )
    }
    

    navigate('/article')
   }

   //获取图片类型
   const [imgeType,setImageType] =useState(0)
   const  onTypeChange=(e)=>{
        
        setImageType(parseInt(e.target.value))
   }

   //获取图片信息
    const [imageList, setImageList] = useState([])
    const onImagesChange  =(value)=>{
        setImageList(value.fileList)
    }

  //获取地址信息
  const  [searchParam]= useSearchParams()
  const articleId = searchParam.get('id')
  
  //获取组件实例
  const [form] = Form.useForm()
  //通过ID获取文章信息
   useEffect( ()=>{

      // 1、通过ID获取数据
      const getActiveInfo =async ()=>{
         const res = await getActiveByIdAPI(articleId)
         const data = res.data.data
         //2、调用实例方法完成回填
         form.setFieldsValue({
          ...data,

           type: data.cover.type,  //封面的类型
           
         })
         //为什么现在的写法无法回填封面？
         //数据结构的问题set方法->{type:3}{cover:{type：3}}

         //3、回填图片
         setImageType(data.cover.type)
         setImageList(data.cover.images.map(url=>{
           return {url}
         }))
      }

      //只有有ID的时候才能调用回填
      if(articleId !== null && articleId !=='') {
        getActiveInfo()
      }
      
   },[articleId,form]) 

  
 


    return (
      <div className="publish">
        <Card
          title={
            <Breadcrumb items={[
              { title: <Link to={'/'}>首页</Link> },
              { title: `${articleId ? '编辑文章' :'发布文章'}`  },
            ]}
            />
          }
        >
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ type: imgeType }}
            onFinish={onFinish}
            form ={form}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '请输入文章标题' }]}
            >
              <Input placeholder="请输入文章标题" style={{ width: 400 }} />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择文章频道' }]}
            >
              <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                {channelList.map(item=><Option key ={item.id} value={item.id}>{item.name}</Option> )}
              </Select>
            </Form.Item>
            <Form.Item label="封面">

            {/* 文章封面 */}
            <Form.Item name="type" onChange = {onTypeChange}>
                <Radio.Group>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
                </Radio.Group>
            </Form.Item>
            {imgeType >0 &&(
                 <Upload
                 listType="picture-card"
                 showUploadList
                 action={`${baseURL}/upload`}
                 name='image'
                 onChange={onImagesChange}
                 maxCount ={imgeType}
                 fileList={imageList}
              
               >
                 <div style={{ marginTop: 8 }}>
                   <PlusOutlined />
                 </div>
               </Upload>
            )}
           
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入文章内容' }]}
            >
            {/* 富文本编辑器 */}
            <ReactQuill
                className="publish-quill"
                 theme="snow"
             placeholder="请输入文章内容"
            />

            </Form.Item>
  
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  发布文章
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  
  export default Publish